package com.five.welcome.config.webSocketTask;


import cn.hutool.json.JSONUtil;
import com.five.welcome.config.websockethandler.WebSocketServer;
import com.five.welcome.pojo.AddressCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class WebSocketTask {

    //获取myWebSocket处理类
    @Autowired
    private WebSocketServer webSocketServer;

    //实际报道人数
    public static int nowCount = 5;
    //                河北       天津      河南      山东       浙江      贵州       江西      甘肃
    public static int HBCount = 5, TJCount = 3, HNCount = 6, SDCount = 4, ZJCount = 5, GZCount = 2, JXCount = 4, GSCount = 3;

    /**
     * 通过WebSocket每隔5秒向客户端发送消息
     * 频率(每五秒)
     * 发送未缴费和已缴费和实际报道人数
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessageToClient() {
        //获取要发送的消息(可以是字符串,JSON字符串)用map接收
        Map<String, Object> data = getData();
        int o = (int) data.get("nowCount");
        if (o > 1210) {
            data.put("nowCount", 1210);
            data.put("unpaid", 5);
            data.put("paid", 1205);
        }
        //转成JSON字符串
        String jsonStr = JSONUtil.toJsonStr(data);
        //发送
        webSocketServer.sendMessage(jsonStr, "count3");
    }

    /*
    向前端发送每个地点的报到人数
    频率五秒
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void sendMessageToOneClient() {
        //获取要发送的消息(可以是字符串,JSON字符串)用map接收
        List<AddressCount> oneData = getOneData();
        //转成JSON字符串
        String jsonStr = JSONUtil.toJsonStr(oneData);
        //发送
        webSocketServer.sendMessage(jsonStr, "110");
    }

    public List<AddressCount> getOneData() {
        Random random = new Random();
        HBCount += random.nextInt(10);
        TJCount += random.nextInt(4);
        HNCount += random.nextInt(6);
        SDCount += random.nextInt(5);
        ZJCount += random.nextInt(7);
        GZCount += random.nextInt(8);
        JXCount += random.nextInt(5);
        GSCount += random.nextInt(4);

        return Arrays.asList(new AddressCount("河北", HBCount), new AddressCount("天津", TJCount),
                new AddressCount("河南", HNCount), new AddressCount("山东", SDCount),
                new AddressCount("浙江", ZJCount), new AddressCount("甘肃", GSCount),
                new AddressCount("江西", JXCount), new AddressCount("贵州", GZCount));
    }

    // 模拟从数据库中查询数据
    private Map<String, Object> getData() {
        int total = 1210;
        Random random = new Random();
        int add = random.nextInt(20) + 5;
        nowCount += add;
        int paid = nowCount - (random.nextInt(5));
        Map<String, Object> map = new HashMap<>();
        map.put("unpaid", total - paid);
        map.put("paid", paid);
        map.put("nowCount", nowCount);
        return map;
    }
}
